package com.live.dengdengtv.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import android.content.Context;
import android.os.Environment;

import com.live.dengdengtv.exception.SDCardNotExistException;


public class FileUtils {

	public static boolean isSDCardExit() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	public static String getSDPath() throws SDCardNotExistException {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			throw new SDCardNotExistException();
		}
		return Environment.getExternalStorageDirectory() + "/";
	}

	public static File getFile(String path, String fileName)
			throws SDCardNotExistException {
		if (path != null && path.startsWith("/")) {
			path = path.substring(1);
		}
		return new File(getSDPath() + path, fileName);
	}

	public static File getMemoryFile(Context context, String fileName) {
		File file = null;
		try {
			file = new File(context.getFilesDir().getAbsolutePath()
					+ File.separator + fileName);
			if (file.exists()) {
				return file;
			} else {
				file = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	/**
	 * 在SD卡上创建文件
	 * 
	 * @param fileName
	 * @return
	 * @throws IOException
	 * @throws SDCardNotExistException
	 */
	public static File createSDFile(String fileName) throws IOException,
			SDCardNotExistException {
		File file = new File(fileName);
		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();
		return file;
	}

	/**
	 * 在SD卡上创建目录
	 * 
	 * @param dirName
	 * @return
	 * @throws SDCardNotExistException
	 */
	public static File createSDDir(String dirName)
			throws SDCardNotExistException {
		if (dirName != null && dirName.startsWith("/")) {
			dirName = dirName.substring(1);
		}
		File dir = new File(getSDPath() + dirName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	/**
	 * 判断SD卡上的文件夹是否存在
	 * 
	 * @return
	 * @throws SDCardNotExistException
	 */
	public static boolean isDirExist(String dirName)
			throws SDCardNotExistException {
		File file = new File(getSDPath() + dirName);
		return file.exists();
	}

	/**
	 * 判断SD卡上的文件是否存在
	 * 
	 * @param fileName
	 * @return
	 * @throws SDCardNotExistException
	 */
	public static boolean isFileExist(String fileName)
			throws SDCardNotExistException {
		File file = new File(getSDPath(), fileName);
		return file.exists();
	}

	/**
	 * 判断SD卡上的文件夹是否存在
	 * 
	 * @param fileName
	 * @return
	 * @throws SDCardNotExistException
	 */
	public static boolean isFileExist(String path, String fileName)
			throws SDCardNotExistException {
		return isFileExist(path + fileName);
	}

	/**
	 * 在SDCard创建文件，存在则删除后，创建
	 * 
	 * @param fileName
	 * @return异常返回null
	 */
	public static File createSdcardFile(String fileName) {
		try {
			String filePath = Environment.getExternalStorageDirectory()
					+ File.separator + fileName;
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			}
			if (file.createNewFile()) {
				return file;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static File createMemeryFile(Context context, String fileName) {
		try {
			String filePath = context.getFilesDir().getAbsolutePath()
					+ File.separator + fileName;
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			}
			if (file.createNewFile()) {
				return file;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void deleteSDFile(String fileName)
			throws SDCardNotExistException {
		if(fileName == null) return;
		File file = new File(getSDPath(), fileName);
		System.out.println("文件路径为："+file.getAbsolutePath());
		if (file != null && file.exists()) {
			file.delete();
		}
	}

	/**
	 * 不管路径是文件还是文件夹，都删掉
	 * 
	 * @param fileName
	 * @return
	 * @throws SDCardNotExistException
	 */
	public static boolean delete(String fileName)
			throws SDCardNotExistException {
		return delete(FileUtils.getFile("", fileName));
	}

	/**
	 * 不管路径是文件还是文件夹，都删掉
	 * 
	 * @param file
	 * @return
	 */
	public static boolean delete(File file) {
		if (!file.exists()) {
			System.out.println("文件或文件夹不存在：" + file);
			return false;
		}
		if (file.isFile()) {
			return file.delete();
		} else {
			return deleteDir(file);
		}
	}

	/**
	 * 删除文件夹，且删除自己本身
	 * 
	 */
	private static boolean deleteDir(File dir) {
		try {
			return deleteFromDir(dir) && dir.delete(); // 先删除完里面所有内容再删除空文件夹
		} catch (Exception e) {
			System.out.println("删除文件夹操作出错");
			// e.printStackTrace();
			return false;
		}
	}

	/**
	 * 删除文件夹里面的所有文件,但不删除自己本身
	 * 
	 * @return
	 * @throws SDCardNotExistException
	 */
	public static boolean deleteFromDir(String dirPath)
			throws SDCardNotExistException {
		File file = FileUtils.getFile("", dirPath);
		return deleteFromDir(file);
	}

	/**
	 * 删除文件夹里面的所有文件,但不删除自己本身
	 * 
	 * @return
	 */
	public static boolean deleteFromDir(File dir) {
		if (!dir.exists()) {
			System.out.println("文件夹不存在：" + dir);
			return false;
		}
		if (!dir.isDirectory()) {
			System.out.println(dir + "不是文件夹");
			return false;
		}
		File[] tempList = dir.listFiles();
		for (int i = 0; i < tempList.length; i++) {
			if (!delete(tempList[i])) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 将一个InputStream里面的数据写入到SD卡中
	 * 
	 * @param path
	 * @param fileName
	 * @param input
	 * @return
	 * @throws Exception
	 */
	public static File write2SDFromInput(String path, String fileName,
			InputStream input) throws Exception {
//		if (path != null && path.startsWith("/")) {
//			path = path.substring(1);
//		}
		File file = null;
		OutputStream output = null;
		try {
			//TODO
			createSDDir(path);
			file = createSDFile(path + "/"+fileName);
			output = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			input.available();
			while ((len = input.read(buffer)) >0) {
				output.write(buffer, 0, len);
			}
			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("写文件到SD卡失败!");
		} finally {
			try {
				output.close();
				output = null;
			} catch (IOException e) {
				throw new Exception("写文件到SD卡时关闭文件流失败!");
			}
		}
		return file;
	}

	public static boolean writeByte(String fileName, byte[] b) {
		try {
			BufferedOutputStream fos = new BufferedOutputStream(
					new FileOutputStream(fileName));
			fos.write(b);
			fos.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static boolean writeByte(File f, byte[] b) {
		try {
			BufferedOutputStream fos = new BufferedOutputStream(
					new FileOutputStream(f));
			fos.write(b);
			fos.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public String readTxtFile(String fileName) throws SDCardNotExistException {
		// 取得文本文件
		File file = getFile(null, fileName);
		// 存储内容的文本对象
		StringBuilder text = new StringBuilder();

		try {
			FileInputStream fileIS = new FileInputStream(file);
			BufferedReader br = new BufferedReader(
					new InputStreamReader(fileIS));
			String line;

			while ((line = br.readLine()) != null) {
				text.append(line);
				text.append('\n');
			}
			br.close();
			fileIS.close();
		} catch (IOException e) {
			// 增加异常处理
		}
		return text.toString();
	}

	public static boolean copy(String oldPath, String newPath, FileFilter filter) {
		File oldFile = new File(oldPath);
		File[] oldFiles = oldFile.listFiles(filter);
		boolean flag = true;
		if (oldFiles != null) {
			for (int i = 0; i < oldFiles.length; i++) {
				if (!copy(oldFiles[i], newPath + "/" + oldFiles[i].getName())) {
					flag = false;
				}
			}
		}
		return flag;
	}

	public static boolean copy(String oldPath, String newPath) {
		File oldFile = new File(oldPath);
		return copy(oldFile, newPath);
	}

	public static boolean copy(File oldFile, String newPath) {
		if (!oldFile.exists()) {
			System.out.println("文件或者文件夹不存在：" + oldFile);
			return false;
		}
		if (oldFile.isFile()) {
			return copyFile(oldFile, newPath);
		} else {
			return copyDir(oldFile, newPath);
		}
	}

	/**
	 * 复制单个文件
	 * 
	 * @param oldFile
	 * @param newPath
	 * @return boolean
	 */
	private static boolean copyFile(File oldFile, String newPath) {
		if (!oldFile.exists()) { // 文件存在时
			System.out.println("文件不存在：" + oldFile);
			return false;
		}
		if (!oldFile.isFile()) { // 文件存在时
			System.out.println(oldFile + "不是文件");
			return false;
		}
		try {
			int byteread = 0;
			InputStream inStream = new FileInputStream(oldFile); // 读入原文件
			FileOutputStream fs = new FileOutputStream(newPath);
			byte[] buffer = new byte[1024];
			while ((byteread = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
			}
			fs.close();
			inStream.close();
		} catch (Exception e) {
			System.out.println("复制单个文件" + oldFile.getPath() + "操作出错。错误原因:"
					+ e.getMessage());
			// e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 复制整个文件夹内容
	 * 
	 * @param oldDir
	 * @param newPath
	 * @return boolean
	 */
	private static boolean copyDir(File oldDir, String newPath) {
		if (!oldDir.exists()) { // 文件存在时
			System.out.println("文件夹不存在：" + oldDir);
			return false;
		}
		if (!oldDir.isDirectory()) { // 文件存在时
			System.out.println(oldDir + "不是文件夹");
			return false;
		}
		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File[] files = oldDir.listFiles();
			File temp = null;
			for (int i = 0; i < files.length; i++) {
				temp = files[i];
				if (temp.isFile()) {
					if (!copyFile(temp, newPath + "/" + temp.getName())) {
						return false;
					}
				} else if (temp.isDirectory()) {// 如果是子文件夹
					if (!copyDir(temp, newPath + "/" + temp.getName())) {
						return false;
					}
				}
			}
			return true;
		} catch (Exception e) {
			System.out.println("复制整个文件夹内容操作出错。错误原因:" + e.getMessage());
			// e.printStackTrace();
			return false;
		}
	}

	public void convertCodeAndGetText(String path) {// 转码

		StringBuffer stringBuffer = new StringBuffer();

		File file = new File(path);

		BufferedReader reader;
		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream in = new BufferedInputStream(fis);
			in.mark(4);
			byte[] first3bytes = new byte[3];
			in.read(first3bytes);// 找到文档的前三个字节并自动判断文档类型。
			in.reset();
			if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB
					&& first3bytes[2] == (byte) 0xBF) {// utf-8
				reader = new BufferedReader(new InputStreamReader(in, "utf-8"));

			} else if (first3bytes[0] == (byte) 0xFF
					&& first3bytes[1] == (byte) 0xFE) {
				reader = new BufferedReader(
						new InputStreamReader(in, "unicode"));
			} else if (first3bytes[0] == (byte) 0xFE
					&& first3bytes[1] == (byte) 0xFF) {
				reader = new BufferedReader(new InputStreamReader(in,
						"utf-16be"));
			} else if (first3bytes[0] == (byte) 0xFF
					&& first3bytes[1] == (byte) 0xFF) {
				reader = new BufferedReader(new InputStreamReader(in,
						"utf-16le"));
			} else {
				reader = new BufferedReader(new InputStreamReader(in, "GBK"));
			}

			String str;

			while ((str = reader.readLine()) != null) {
				stringBuffer.append(str + "\n");
			}
			reader.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
